using Avalonia.Controls;
using Avalonia.Interactivity;
using IntegratedMeasuring.ViewModels.Scheme;
using IntegratedMeasuring.Storage;
using System;
using System.Linq;
using System.ComponentModel;
using IntegratedMeasuring.Utils;

namespace IntegratedMeasuring.Pages;

public partial class OrderEditDialog : Window, INotifyPropertyChanged
{
    public ProductionOrder? EditedOrder { get; private set; }
    public event PropertyChangedEventHandler? PropertyChanged;

    private bool _isTestFileEditable = true;
    public bool IsTestFileEditable
    {
        get => _isTestFileEditable;
        set
        {
            if (_isTestFileEditable != value)
            {
                _isTestFileEditable = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsTestFileEditable)));
            }
        }
    }

    public Func<string, string, bool>? CheckOrderBatchExists; // 委托用于唯一性校验
    public Action<ProductionOrder>? SaveNewBatchAction; // 委托用于保存新周期

    public OrderEditDialog(ProductionOrder? order = null)
    {
        InitializeComponent();
        DataContext = this;
        LoadTestConditionsAsync();

        if (order != null)
        {
            // 编辑模式
            NameTextBox.Text = order.Name ?? string.Empty;
            BatchNumberTextBox.Text = order.BatchNumber ?? string.Empty;
            PlanNumberTextBox.Text = order.PlanNumber.ToString();
            RemarksTextBox.Text = order.Remarks ?? string.Empty;
            AllowOverflowCheckBox.IsChecked = order.AllowOverflow;
            // 设置选中的测试文件
            TestConditionsComboBox.SelectedItem = order.TestConditions;
            // 如果该周期下有测试记录，则禁用测试文件选择
            if (order.PassNumber > 0 || order.FailNumber > 0)
            {
                IsTestFileEditable = false;
            }
        }
        else
        {
            var lastOrders = BaseDataStorage.Instance.GetLastUsedOrders();

            if (lastOrders != null)
            {
                NameTextBox.Text = lastOrders.Name ?? string.Empty;
                TestConditionsComboBox.SelectedItem = lastOrders.TestConditions;
            }


            // 新增时隐藏存为新周期按钮
            SaveAsNewBatchButton.IsVisible = false;
        }
    }

    private async void LoadTestConditionsAsync()
    {
        try
        {
            var testConditions = await BaseDataStorage.Instance.LoadTestConditionsListAsync();
            var names = testConditions.Select(tc => tc.Name).ToList();
            TestConditionsComboBox.ItemsSource = names;

            if (names.Count > 0)
            {
                // TestConditionsComboBox.SelectedIndex = 0;
            }
        }
        catch (Exception ex)
        {
            // 可以添加错误处理
        }
    }

    private void OkButton_Click(object? sender, RoutedEventArgs e)
    {
        // 验证输入
        if (string.IsNullOrWhiteSpace(NameTextBox.Text))
        {
            NotificationHelper.ShowError("输入错误", "工单名称不能为空");
            return;
        }
        if (string.IsNullOrWhiteSpace(BatchNumberTextBox.Text))
        {
            NotificationHelper.ShowError("输入错误", "周期号不能为空");
            return;
        }
        if (!int.TryParse(PlanNumberTextBox.Text, out int planNumber))
        {
            NotificationHelper.ShowError("输入错误", "计划数量必须为数字");
            return;
        }
        // 唯一性校验
        if (CheckOrderBatchExists != null && CheckOrderBatchExists(NameTextBox.Text.Trim(), BatchNumberTextBox.Text.Trim()))
        {
            NotificationHelper.ShowError("保存失败", "同工单号下周期号不可重复！");
            return;
        }
        EditedOrder = new ProductionOrder
        {
            Name = NameTextBox.Text.Trim(),
            BatchNumber = BatchNumberTextBox.Text.Trim(),
            TestConditions = TestConditionsComboBox.SelectedItem?.ToString() ?? string.Empty,
            PlanNumber = planNumber,
            Remarks = RemarksTextBox.Text?.Trim() ?? string.Empty,
            AllowOverflow = AllowOverflowCheckBox.IsChecked ?? false
        };
        this.Close(true);
    }

    private void SaveAsNewBatchButton_Click(object? sender, RoutedEventArgs e)
    {
        // 验证输入
        if (string.IsNullOrWhiteSpace(NameTextBox.Text))
        {
            NotificationHelper.ShowError("输入错误", "工单名称不能为空");
            return;
        }
        if (string.IsNullOrWhiteSpace(BatchNumberTextBox.Text))
        {
            NotificationHelper.ShowError("输入错误", "周期号不能为空");
            return;
        }
        if (!int.TryParse(PlanNumberTextBox.Text, out int planNumber))
        {
            NotificationHelper.ShowError("输入错误", "计划数量必须为数字");
            return;
        }
        // 唯一性校验
        if (CheckOrderBatchExists != null && CheckOrderBatchExists(NameTextBox.Text.Trim(), BatchNumberTextBox.Text.Trim()))
        {
            NotificationHelper.ShowError("保存失败", "同工单号下周期号不可重复！");
            return;
        }
        var newOrder = new ProductionOrder
        {
            Id = 0, // 新周期Id清空
            Name = NameTextBox.Text.Trim(),
            BatchNumber = BatchNumberTextBox.Text.Trim(),
            TestConditions = TestConditionsComboBox.SelectedItem?.ToString() ?? string.Empty,
            PlanNumber = planNumber,
            PassNumber = 0,
            FailNumber = 0,
            Remarks = RemarksTextBox.Text?.Trim() ?? string.Empty,
            AllowOverflow = AllowOverflowCheckBox.IsChecked ?? false,
            CreateTime = DateTime.Now
        };
        SaveNewBatchAction?.Invoke(newOrder);
        this.Close(false);
    }

    private void CancelButton_Click(object? sender, RoutedEventArgs e)
    {
        this.Close(false);
    }
}